package com;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zhuhaibo
 * @version 1.0
 * @date 2021/3/14 22:47
 */
@Slf4j
public class JsonTest {

    /**
     * 读取json文件
     *
     * @param fileName
     * @return
     */
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            int ch = 0;
            StringBuilder sb = new StringBuilder();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
        String path = Objects.requireNonNull(JsonTest.class.getClassLoader().getResource("template/insitution.json")).getPath();
        String s = readJsonFile(path);
        JSONObject jsonObject = JSON.parseObject(s);
        // 构建JSONArray数组
        JSONArray movies = jsonObject.getJSONArray("result");
        Map<Integer, String> errorMsgMap = new HashMap<>();
        int count = 0;
        for (Object movie : movies) {
            JSONObject key = (JSONObject) movie;
            String errorMsg = (String) key.get("errorMsg");
            Integer lineNo = (Integer) key.get("lineNo");
            errorMsgMap.put(lineNo, errorMsg);
            count++;
        }
        System.out.println("重复数据条数：" + count);

        BiConsumer<Integer, String> integerStringBiConsumer = (k, v) -> {
            // 正则获取单位名称，单位类型
            String regexName = "(?<=单位名称).+(?=在单位类型)";
            String regexType = "(?<=单位类型).+(?=下)";
            String name = findName(regexName, v).trim();
            String type = findName(regexType, v).trim();
            errorMsgMap.put(k, MessageFormat.format("{0}_{1}", name, type));
            log.info("单位名称：{}_单位类型{}",name,type);
        };
        errorMsgMap.forEach(integerStringBiConsumer);
        log.info("errorMsgMap{}",errorMsgMap);
    }

    private static String findName(String regex, String v) {
        Pattern r = Pattern.compile(regex);
        Matcher m = r.matcher(v);
        m.find();
        return m.group();
    }
}
